var tableIns;//表格实例
var style = 'macarons2';
let map = new Map();
let layTable;
let form;
layui.use(['laydate', 'form', 'table'], function() {
	form = layui.form;
	io.get("/ep/data/comm_query_stock_list", function(res) {
		for (let v of res.data) {
			map.set(v.ts_code, v.name);
		}
		map2Select(map, 'stock');
		form.render(null, "cForm");
	});
	var laydate = layui.laydate;
	layTable = layui.table;
	let today = new Date();
	let twoYearsAgo = new Date();
	twoYearsAgo.setFullYear(today.getFullYear() - 5);
	laydate.render({
		elem: '#startDate'
		, type: 'date'
		, format: 'yyyyMMdd'
		, value: twoYearsAgo
	});
	laydate.render({
		elem: '#endDate'
		, type: 'date'
		, format: 'yyyyMMdd'
		, value: today
	});

	form.on('submit(search)', function(formData) {
		var tsCode = formData.field.stock;
		var startDate = formData.field.startDate;
		var endDate = formData.field.endDate;
		renderCompany(tsCode);
		renderHoldernumber(tsCode, startDate, endDate);
		renderHolders(tsCode, startDate, endDate);
		renderIndicators(formData.field);
		renderForecast(tsCode, startDate, endDate);
		renderMainBz(tsCode, startDate, endDate);
		renderBlockTrade(tsCode, startDate, endDate);
		renderFloatholder(tsCode, startDate, endDate);
		renderRepurchase(tsCode, startDate, endDate);
		renderHoldertrade(tsCode, startDate, endDate);
	});

});

function renderCompany(tsCode) {
	io.get("/stock/company?tsCode=" + tsCode, function(res) {
		$("#dForm").show();
		form.val("dForm", res.data);
	});
}

function renderHoldernumber(tsCode, startDate, endDate) {
	io.get("/stock/single/holdernumber?tsCode=" + tsCode + "&startDate=" + startDate + "&endDate=" + endDate, function(res) {
		renderLine("holdernumber", res, "股东人数");
	});
}

function renderHolders(tsCode, startDate, endDate) {
	var holdersStacks = echarts.init(document.getElementById('holders'), style);
	holdersStacks.showLoading();
	var holdersOption = {
		title: {
			text: '股东占比分析',
			left: 'center'
		},
		tooltip: {
			trigger: 'axis',
			axisPointer: {            // 坐标轴指示器，坐标轴触发有效
				type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
			}, formatter: function(params) {
				//x轴的名称
				params = params.sort((a, b) => b.value - a.value)
				var htmlStr = params[0].name + '<br/>';
				for (var i = 0; i < params.length; i++) {
					var param = params[i];
					if (param.value > 0) {
						htmlStr += '<div>';
						//为了保证和原来的效果一样，复制的是：param.marker的源码，圆点样式：param.color
						htmlStr += '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:' + param.color + ';"></span>';
						// 名称颜色设置
						// htmlStr += '<span style="color:'+param.color+'">';
						//圆点后面显示的名称
						htmlStr += param.seriesName + '：' + param.value;
						// htmlStr += '</span>';
						htmlStr += '</div>';
					}
				}
				return htmlStr;
			}
		},
		legend: {
			show: false
		},
		grid: {
			left: '3%',
			right: '4%',
			bottom: '3%',
			containLabel: true
		},
		yAxis: [
			{
				axisLabel: { formatter: '{value}' },
				type: 'value'
			}
		]
	};
	io.get("/stock/single/holders?tsCode=" + tsCode + "&startDate=" + startDate + "&endDate=" + endDate, function(res) {
		holdersStacks.hideLoading();
		holdersOption.legend.data = res.attr.legendData;
		holdersOption.xAxis = [{ axisLabel: { interval: 0, rotate: 40 }, type: 'category', data: res.attr.xAxisData }];
		holdersOption.series = res.attr.series;
		holdersStacks.setOption(holdersOption,true);
	});
}

function renderIndicators(params) {
	$('#title').html(map.get(params.stock) + "(" + params.stock + ")");
	//交易指标
	_render(params, "bi_stock_indicators", "d_stock_mv", "total_mv", "mv", "总市值", 10000);
	_render(params, "bi_stock_indicators", "d_stock_mv", "pe_ttm", "pettm", "PE-TTM");
	_render(params, "bi_stock_indicators", "d_stock_mv", "close", "close", "股票价格");
	_render(params, "bi_stock_indicators", "d_stock_mv", "pb", "pb", "市净率");
	_render(params, "bi_stock_indicators", "d_stock_mv", "dv_ttm", "dvttm", "股息率TTM(%)");
	_render(params, "bi_stock_indicators", "d_stock_mv", "ps_ttm", "psttm", "市销率TTM(%)");
	//收入指标
	params.sqlid="bi_stock_indicators"; //按财报期统计数据，当期财报没数据的会补0
	params.tableName = "d_stock_income";
	params.indicatorField = "total_revenue";
	params.unit = 10000 * 10000;
	io.get("/stock/single/indicators", function(res) {
		params.tableName = "d_stock_income";
		params.indicatorField = "total_cogs";
		io.get("/stock/single/indicators", function(res2) {
			renderLine2("total_revenue", "收入/成本", ["总收入", "总成本"], res.attr.category, [res.attr.data, res2.attr.data]);
		}, params);
	}, params);
	params.tableName = "d_stock_fina_indicator";
	params.indicatorField = "gross_margin";
	io.get("/stock/single/indicators", function(res) {
		params.tableName = "d_stock_income";
		params.indicatorField = "n_income_attr_p";
		io.get("/stock/single/indicators", function(res2) {
			params.tableName = "d_stock_fina_indicator";
			params.indicatorField = "profit_dedt";
			io.get("/stock/single/indicators", function(res3) {
				renderLine2("gross_margin", "利润", ["毛利润", "净利润", "净利润（扣非）"], res.attr.category, [res.attr.data, res2.attr.data, res3.attr.data]);
			}, params);
		}, params);
	}, params);
	params.tableName = "d_stock_income";
	params.indicatorField = "sell_exp";
	io.get("/stock/single/indicators", function(res) {
		params.tableName = "d_stock_income";
		params.indicatorField = "admin_exp";
		io.get("/stock/single/indicators", function(res2) {
			params.tableName = "d_stock_income";
			params.indicatorField = "fin_exp";
			io.get("/stock/single/indicators", function(res3) {
				params.tableName = "d_stock_income";
				params.indicatorField = "oper_cost";
				io.get("/stock/single/indicators", function(res4) {
					renderLine2("fees", "费用", ["销售费用", "管理费用", "财务费用", "营业成本"], res.attr.category, [res.attr.data, res2.attr.data, res3.attr.data, res4.attr.data]);
				}, params);
			}, params);
		}, params);
	}, params);
	_render(params, "bi_stock_indicators", "d_stock_income", "assets_impair_loss", "assets_impair_loss", "资产减值损失", 10000 * 10000);
	_render(params, "bi_stock_indicators", "d_stock_fina_indicator", "extra_item", "extra_item", "非经常性损益", 10000 * 10000);

	//财务指标
	_render(params, "bi_stock_indicators", "d_stock_fina_indicator", "eps", "eps", "基本每股收益");
	_render(params, "bi_stock_indicators", "d_stock_fina_indicator", "saleexp_to_gr", "saleexp_to_gr", "销售费用/营业总收入");
	_render(params, "bi_stock_indicators", "d_stock_fina_indicator", "fcff", "fcff", "企业自由现金流量", 10000 * 10000);
	_render(params, "bi_stock_indicators", "d_stock_fina_indicator", "roe", "roe", "净资产收益率");
	_render(params, "bi_stock_indicators", "d_stock_fina_indicator", "roic", "roic", "投入资本回报率");
	_render(params, "bi_stock_indicators", "d_stock_fina_indicator", "debt_to_assets", "debt_to_assets", "资产负债率");
	_render(params, "bi_stock_indicators", "d_stock_fina_indicator", "q_profit_yoy", "q_profit_yoy", "净利润同比增长率(%)(单季度)");
	_render(params, "bi_stock_indicators", "d_stock_fina_indicator", "rd_exp", "rd_exp", "研发费用", 10000 * 10000);
	//资产负债
	params.tableName = "d_stock_balancesheet";
	params.indicatorField = "total_assets";
	params.unit = 10000 * 10000;
	io.get("/stock/single/indicators", function(res) {
		params.tableName = "d_stock_balancesheet";
		params.indicatorField = "total_liab";
		io.get("/stock/single/indicators", function(res2) {
			renderLine2("total_assets", "资产负债", ["资产", "负债"], res.attr.category, [res.attr.data, res2.attr.data]);
		}, params);
	}, params);
	_render(params, "bi_stock_indicators", "d_stock_balancesheet", "inventories", "inventories", "存货", 10000 * 10000);
	_render(params, "bi_stock_indicators", "d_stock_balancesheet", "goodwill", "goodwill", "商誉", 10000 * 10000);
	//现金流量
	_render(params, "bi_stock_indicators", "d_stock_cashflow", "n_cash_flows_fnc_act", "n_cash_flows_fnc_act", "筹资活动产生的现金流量净额", 10000 * 10000);
	_render(params, "bi_stock_indicators", "d_stock_cashflow", "n_incr_cash_cash_equ", "n_incr_cash_cash_equ", "现金及现金等价物净增加额", 10000 * 10000);
}

function _render(params, sqlid, table, field, elementId, title, unit) {
	var _params = { ...params };
	_params.sqlid = sqlid;
	_params.tableName = table;
	_params.indicatorField = field;
	if (unit) {
		_params.unit = unit;
	} else {
		_params.unit = 1;
	}
	io.get("/stock/single/indicators", function(res) {
		renderLine(elementId, res, title);
	}, _params);
}

function renderLine(elementId, data, title) {
	var line = echarts.init(document.getElementById(elementId), style);
	option = {
		title: {
			text: title,
			left: 'center'
		},
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'cross'
			}
		},
		xAxis: {
			type: 'category',
			data: data.attr.category
		},
		yAxis: {
			type: 'value'
		},
		series: [
			{
				data: data.attr.data,
				type: 'line',
				stack: 'Total',
				label: {
					show: true,
					position: 'top'
				},
				areaStyle: {},
				emphasis: {
					focus: 'series'
				},
			}
		]
	};
	line.setOption(option);
}

function renderLine2(elementId, title, legend, category, data) {
	var line = echarts.init(document.getElementById(elementId), style);
	option = {
		title: {
			text: title
		},
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'cross'
			}
		},
		legend: {
		},
		xAxis: {
			type: 'category',
			boundaryGap: false,
			data: category
		},
		yAxis: {
			type: 'value'
		},
	};
	var series = [];
	for (var i = 0; i < data.length; i++) {
		series[i] = {
			name: legend[i],
			data: data[i],
			type: 'line',
			label: {
				show: true,
				position: 'top'
			},
		};
	}
	option.series = series;
	line.setOption(option);
}

function renderForecast(tsCode, startDate, endDate) {
	layTable.render({
		elem: '#forecastTable'
		, url: appendCtx("/stock/single/forecast?tsCode=" + tsCode + "&startDate=" + startDate + "&endDate=" + endDate)
		, height: 500
		, even: true
		, cols: [[ //表头
			, { field: 'tsCode', title: 'TS代码', align: 'center', width: 100 }
			, { field: 'endDate', title: '报告期', align: 'center', width: 100 }
			, { field: 'type', title: '预期', align: 'center', width: 100 }
			, {
				field: 'pChangeMin', title: '变化前值', align: 'right', width: 100, templet:
					function(d) { if (d.pChangeMin != -2147483648.00) { return numberFormat(d.pChangeMin, 2) + '%'; } return '-'; }
			}, {
				field: 'pChangeMax', title: '变化后值', align: 'right', width: 100, templet:
					function(d) { if (d.pChangeMax != -2147483648.00) { return numberFormat(d.pChangeMax, 2) + '%'; } return '-'; }
			}, {
				field: 'netProfitMin', title: '净利润前值', align: 'right', width: 100, templet:
					function(d) { if (d.netProfitMin != -2147483648.00) { return numberFormat(d.netProfitMin / 10000, 2); } return '-'; }
			}, {
				field: 'netProfitMax', title: '净利润后值', align: 'right', width: 100, templet:
					function(d) { if (d.netProfitMax != -2147483648.00) { return numberFormat(d.netProfitMax / 10000, 2); } return '-'; }
			}, {
				field: 'lastParentNet', title: '去年同期', align: 'right', width: 100, templet:
					function(d) { if (d.lastParentNet != -2147483648.00) { return numberFormat(d.lastParentNet / 10000, 2); } return '-'; }
			}, {
				field: 'summary', title: '摘要', align: 'left', width: 300
			}, {
				field: 'changeReason', title: '变化原因', align: 'left', width: 400
			}
		]]
		, page: {
			limit: 10,
			limits: [10, 30, 50, 100]
		}
		, request: {
			pageName: 'pageNo' //页码的参数名称，默认：page
			, limitName: 'pageSize' //每页数据量的参数名，默认：limit
		}
		, parseData: function(res) { //res 即为原始返回的数据
			return {
				"code": res.code, //解析接口状态
				"msg": res.msg, //解析提示文本
				"count": res.data.total, //解析数据长度
				"data": res.data.list //解析数据列表
				, "attr": res.attr
			};
		},
	});
}

function renderMainBz(tsCode, startDate, endDate) {
	layTable.render({
		elem: '#mainBzTable'
		, url: appendCtx("/stock/single/mainbz?tsCode=" + tsCode + "&startDate=" + startDate + "&endDate=" + endDate)
		, height: 500
		, even: true
		, cols: [[ //表头
			, { field: 'tsCode', title: 'TS代码', align: 'center', width: 100 }
			, { field: 'endDate', title: '报告期', align: 'center', width: 100 }
			, { field: 'bzItem', title: '来源', align: 'center', width: 400 }
			, {
				field: 'bzSales', title: '收入(亿)', align: 'right', width: 200, templet:
					function(d) { if (d.bzSales != -2147483648.00) { return numberFormat(d.bzSales / 100000000, 2); } return '-'; }
			}, {
				field: 'bzProfit', title: '利润(亿)', align: 'right', width: 200, templet:
					function(d) { if (d.bzProfit != -2147483648.00) { return numberFormat(d.bzProfit / 100000000, 2); } return '-'; }
			}, {
				field: 'bzCost', title: '成本(亿)', align: 'right', width: 200, templet:
					function(d) { if (d.bzSales != -2147483648.00) { return numberFormat(d.bzCost / 100000000, 2); } return '-'; }
			}
		]]
		, page: {
			limit: 10,
			limits: [10, 30, 50, 100]
		}
		, request: {
			pageName: 'pageNo' //页码的参数名称，默认：page
			, limitName: 'pageSize' //每页数据量的参数名，默认：limit
		}
		, parseData: function(res) { //res 即为原始返回的数据
			return {
				"code": res.code, //解析接口状态
				"msg": res.msg, //解析提示文本
				"count": res.data.total, //解析数据长度
				"data": res.data.list //解析数据列表
				, "attr": res.attr
			};
		},
	});
}

function renderBlockTrade(tsCode, startDate, endDate) {
	layTable.render({
		elem: '#blockTradeTable'
		, url: appendCtx("/stock/single/blocktrade?tsCode=" + tsCode + "&startDate=" + startDate + "&endDate=" + endDate)
		, height: 500
		, even: true
		, cols: [[ //表头
			, { field: 'tsCode', title: 'TS代码', align: 'center', width: 100 }
			, { field: 'tradeDate', title: '交易日期', align: 'center', width: 100 }
			, {
				field: 'price', title: '成交价', align: 'right', width: 200, templet:
					function(d) { if (d.price) { return numberFormat(d.price, 2); } return '-'; }
			}
			, {
				field: 'vol', title: '成交量（万股）', align: 'right', width: 200, templet:
					function(d) { if (d.vol) { return numberFormat(d.vol, 2); } return '-'; }
			}
			, {
				field: 'amount', title: '成交金额（万元）', align: 'right', width: 200, templet:
					function(d) { if (d.amount) { return numberFormat(d.amount, 2); } return '-'; }
			}
			, { field: 'buyer', title: '买方营业部', align: 'center', width: 400 }
			, { field: 'seller', title: '卖方营业部', align: 'center', width: 400 }
		]]
		, page: {
			limit: 10,
			limits: [10, 30, 50, 100]
		}
		, request: {
			pageName: 'pageNo' //页码的参数名称，默认：page
			, limitName: 'pageSize' //每页数据量的参数名，默认：limit
		}
		, parseData: function(res) { //res 即为原始返回的数据
			return {
				"code": res.code, //解析接口状态
				"msg": res.msg, //解析提示文本
				"count": res.data.total, //解析数据长度
				"data": res.data.list //解析数据列表
				, "attr": res.attr
			};
		},
	});
}

function renderFloatholder(tsCode, startDate, endDate) {
	layTable.render({
		elem: '#floatholderTable'
		, url: appendCtx("/stock/single/floatholders?tsCode=" + tsCode + "&startDate=" + startDate + "&endDate=" + endDate)
		, height: 500
		, even: true
		, cols: [[ //表头
			, { field: 'tsCode', title: 'TS代码', align: 'center', width: 100 }
			, { field: 'endDate', title: '报告期', align: 'center', width: 100 }
			, { field: 'holderName', title: '股东名称', align: 'left', width: 300 }
			, { field: 'holderType', title: '股东类型', align: 'left', width: 300 }
			, {
				field: 'holdAmount', title: '持有数量（万股）', align: 'right', width: 200, templet:
					function(d) { if (d.holdAmount) { return numberFormat(d.holdAmount / 10000, 2); } return '-'; }
			}
			, {
				field: 'holdRatio', title: '持有比例（%）', align: 'right', width: 200, templet:
					function(d) { if (d.holdRatio) { return numberFormat(d.holdRatio, 2); } return '-'; }
			}
			, {
				field: 'holdFloatRatio', title: '占流通股本比例(%)', align: 'right', width: 200, templet:
					function(d) { if (d.holdFloatRatio) { return numberFormat(d.holdFloatRatio, 2); } return '-'; }
			}
			, {
				field: 'holdChange', title: '持股变动（万股）', align: 'right', width: 200, templet:
					function(d) { if (d.holdChange && d.holdChange != -2147483648) { return numberFormat(d.holdChange / 10000, 2); } return '-'; }
			}
		]]
		, page: {
			limit: 10,
			limits: [10, 30, 50, 100]
		}
		, request: {
			pageName: 'pageNo' //页码的参数名称，默认：page
			, limitName: 'pageSize' //每页数据量的参数名，默认：limit
		}
		, parseData: function(res) { //res 即为原始返回的数据
			return {
				"code": res.code, //解析接口状态
				"msg": res.msg, //解析提示文本
				"count": res.data.total, //解析数据长度
				"data": res.data.list //解析数据列表
				, "attr": res.attr
			};
		},
	});
}

function renderRepurchase(tsCode, startDate, endDate) {
	layTable.render({
		elem: '#repurchaseTable'
		, url: appendCtx("/stock/single/repurchase?tsCode=" + tsCode + "&startDate=" + startDate + "&endDate=" + endDate)
		, height: 500
		, even: true
		, cols: [[ //表头
			, { field: 'tsCode', title: 'TS代码', align: 'center', width: 100 }
			, { field: 'annDate', title: '公告日期', align: 'center', width: 100 }
			, { field: 'expDate', title: '过期日期', align: 'center', width: 100 }
			, { field: 'proc', title: '进度', align: 'center', width: 200 }
			, {
				field: 'vol', title: '回购数量（万股）', align: 'right', width: 200, templet:
					function(d) { if (d.vol && d.vol != -2147483648) { return numberFormat(d.vol / 10000, 2); } return '-'; }
			}
			, {
				field: 'amount', title: '回购金额（万）', align: 'right', width: 200, templet:
					function(d) { if (d.amount && d.amount != -2147483648) { return numberFormat(d.amount / 10000, 2); } return '-'; }
			}
			, {
				field: 'highLimit', title: '回购最高价', align: 'right', width: 200, templet:
					function(d) { if (d.highLimit && d.highLimit != -2147483648) { return numberFormat(d.highLimit, 2); } return '-'; }
			}
			, {
				field: 'lowLimit', title: '回购最低价', align: 'right', width: 200, templet:
					function(d) { if (d.lowLimit && d.lowLimit != -2147483648) { return numberFormat(d.lowLimit, 2); } return '-'; }
			}
		]]
		, page: {
			limit: 10,
			limits: [10, 30, 50, 100]
		}
		, request: {
			pageName: 'pageNo' //页码的参数名称，默认：page
			, limitName: 'pageSize' //每页数据量的参数名，默认：limit
		}
		, parseData: function(res) { //res 即为原始返回的数据
			return {
				"code": res.code, //解析接口状态
				"msg": res.msg, //解析提示文本
				"count": res.data.total, //解析数据长度
				"data": res.data.list //解析数据列表
				, "attr": res.attr
			};
		},
	});
}

function renderHoldertrade(tsCode, startDate, endDate) {
	layTable.render({
		elem: '#holderTradeTable'
		, url: appendCtx("/stock/single/holdertrade?tsCode=" + tsCode + "&startDate=" + startDate + "&endDate=" + endDate)
		, height: 500
		, even: true
		, cols: [[ //表头
			, { field: 'tsCode', title: 'TS代码', align: 'center', width: 100 }
			, { field: 'annDate', title: '公告日期', align: 'center', width: 100 }
			, { field: 'holderName', title: '股东名称', align: 'left', width: 300 }
			, {
				title: '股东类型', align: 'center', width: 100, templet:
					function(d) {
						if (d.holderType) {
							if (d.holderType == 'C') {
								return "公司";
							} else if (d.holderType == 'G') {
								return "高管";
							} else if (d.holderType == 'P') {
								return "个人";
							} else {
								return d.holderType;
							}
						}
						return '-';
					}
			}
			, {
				title: '类型', align: 'center', width: 100, templet:
					function(d) {
						if (d.inDe) {
							if (d.inDe == 'IN') {
								return "增持";
							} else if (d.inDe == 'DE') {
								return "减持";
							} else {
								return d.holderType;
							}
						}
						return '-';
					}
			}
			, {
				title: '变动数量（万股）', align: 'right', width: 150, templet:
					function(d) { if (d.changeVol && d.changeVol != -2147483648) { return numberFormat(d.changeVol / 10000, 2); } return '-'; }
			}
			, {
				title: '占流通比例（%）', align: 'right', width: 150, templet:
					function(d) { if (d.changeRatio && d.changeRatio != -2147483648) { return numberFormat(d.changeRatio, 2); } return '-'; }
			}
			, {
				title: '变动后持股（万股）', align: 'right', width: 150, templet:
					function(d) { if (d.afterShare && d.afterShare != -2147483648) { return numberFormat(d.afterShare / 10000, 2); } return '-'; }
			}
			, {
				title: '变动后占比例（%）', align: 'right', width: 150, templet:
					function(d) { if (d.afterRatio && d.afterRatio != -2147483648) { return numberFormat(d.afterRatio, 2); } return '-'; }
			}
			, {
				title: '平均交易价格', align: 'right', width: 150, templet:
					function(d) { if (d.avgPrice && d.avgPrice != -2147483648) { return numberFormat(d.avgPrice, 2); } return '-'; }
			}
			, {
				title: '持股总数（万股）', align: 'right', width: 150, templet:
					function(d) { if (d.totalShare && d.totalShare != -2147483648) { return numberFormat(d.totalShare / 10000, 2); } return '-'; }
			}
			, { field: 'beginDate', title: '开始日期', align: 'center', width: 100 }
			, { field: 'closeDate', title: '结束日期', align: 'center', width: 100 }
		]]
		, page: {
			limit: 10,
			limits: [10, 30, 50, 100]
		}
		, request: {
			pageName: 'pageNo' //页码的参数名称，默认：page
			, limitName: 'pageSize' //每页数据量的参数名，默认：limit
		}
		, parseData: function(res) { //res 即为原始返回的数据
			return {
				"code": res.code, //解析接口状态
				"msg": res.msg, //解析提示文本
				"count": res.data.total, //解析数据长度
				"data": res.data.list //解析数据列表
				, "attr": res.attr
			};
		},
	});
}